package tsinghua.smxq.foodprice;


import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import tsinghua.smxq.mc.Constants;
import tsinghua.smxq.mc.R;
import tsinghua.smxq.mc.Session;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/*
 * 参考了csdn网站上的一篇文章：http://blog.csdn.net/kkfdsa132/article/details/6416114
 */
public class HistoryTable extends LinearLayout implements OnClickListener,
														OnItemClickListener, OnItemLongClickListener{
	private Context context;	//上下文
	private GridView gv_titles;	//字段视图
	private GridView gv_body;	//数据视图
	private LinearLayout bottomLayout;	//视图底部布局
	private Button bt_next, bt_pre, bt_first, bt_last,bt_refresh;	//按钮：下一页、上一页、首页、尾页、刷新		
	
	private String[][] items;	//[字段][显示的名称]	
	private SimpleAdapter titlesAdatper;	//字段视图适配器
	private int TableRowCount;			//每页显示条数
	private int pageID;					//当前页码
	private int TotalCount;				//总记录条数
	private int pageCount;				//总页数
	private String[] fields;			//字段名称
	private boolean[] isDesc;			//排序方式标记：false-递增排序，true-递减排序
	private ArrayList<HashMap<String, String>>  dataList = new ArrayList<HashMap<String,String>>();	//数据集合
	private List<History> histories = new ArrayList<History>();
	private History history;
	String date;
	public String foodprice;
	
	URL url;
	Toast toast;
	String result = "";
	
    public HistoryTable(Context context) {
		super(context);
		this.context = context;
	}
    
    public HistoryTable(Context context, String[][] items, int TableRowCount) {
    	super(context);
    	this.context = context;    	
    	this.items = items;    	
    	this.TableRowCount = TableRowCount;
    	
    	//连接服务器更新histories   	
    	updateHistory();
    	
    	//排序方式标记：false-递增排序，true-递减排序
    	isDesc = new boolean[items.length];
    	//当前页码
    	pageID = 0;    	
    	//记录总数
    	TotalCount = this.histories.size();
    	//总页码
    	pageCount = TotalCount%TableRowCount==0? (TotalCount/TableRowCount)-1 : TotalCount/TableRowCount;
    	//DisplayToast("TotalCount:  "+TotalCount+"\npageCount ="+pageCount,Toast.LENGTH_SHORT);
    	//字段名称
    	fields = new String[items.length];
    	for (int i = 0; i < items.length; i++) {
    		fields[i] = items[i][0];
		}
    	
    	setField();	//字段视图
    	setBody();	//数据视图
    	setBottomLayout();	//底部视图
    	setOrientation(LinearLayout.VERTICAL);
//    	setScrollContainer(true);
//    	setLayoutParams(new LayoutParams(500, LayoutParams.WRAP_CONTENT));
    	addView(gv_titles);	//添加视图
    	addView(gv_body);
    	addView(bottomLayout);
    	
    }
    
    public void refresh()
    {
    	//现将原来的去掉
    	//removeView(gv_titles);
    	DisplayToast("正在获得最新数据....",Toast.LENGTH_SHORT);
    	removeView(gv_body);
    	removeView(bottomLayout);
    	//连接服务器更新histories   	
    	updateHistory();    	
    	//排序方式标记：false-递增排序，true-递减排序
    	isDesc = new boolean[items.length];
    	//当前页码
    	pageID = 0;    	
    	//记录总数
    	TotalCount = this.histories.size();
    	//总页码
    	pageCount = TotalCount%TableRowCount==0? TotalCount/TableRowCount-1 : TotalCount/TableRowCount;
    	//字段名称
    	fields = new String[items.length];
    	for (int i = 0; i < items.length; i++) {
    		fields[i] = items[i][0];
		}
    	
    	setField();	//字段视图
    	setBody();	//数据视图
    	setBottomLayout();	//底部视图
    	setOrientation(LinearLayout.VERTICAL);
//    	setScrollContainer(true);
//    	setLayoutParams(new LayoutParams(500, LayoutParams.WRAP_CONTENT));
    	//addView(gv_titles);	//添加视图
    	addView(gv_body);
    	addView(bottomLayout);
    }
    
    
    public void updateHistory()
    {
    	histories.clear();
    	 //连接服务器，更新history.xml文件
        try {
			url = new URL("http://"+Constants.serverIP+":8080/MobileCityServer/queryQuote.do?" +
										"userId="+Session.user.getId());
			result = HttpConnection.httpConnection(url);
			if(result.compareToIgnoreCase("failure") == 0) 
			{
				result = "历史记录更新失败";
			}		
			else if(result.compareToIgnoreCase("")!=0)
			{			
				String[] values = result.split(",");
				int vector;
				int count = values.length / 4;
				for(int i = 0; i < count; i++)
				{
					vector = 4*i;
					history = new History(Id2Name.id2City(Integer.parseInt(values[vector])),Integer.parseInt(values[vector]),Id2Name.id2Food(Integer.parseInt(values[vector+1])),Integer.parseInt(values[vector+1]),values[vector+2],values[vector+3]);
					histories.add(history);
				}
				result = "菜价记录更新成功";
			}
			else
			{
				result = "历史记录更新失败，下次联网操作时将得到更新";
			}
		
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
   
    /**
     * 设置字段视图
     */
    private void setField() {
    	gv_titles = new GridView(context);
    	gv_titles.setNumColumns(items.length);
    	
    	//字段标题
    	ArrayList<HashMap<String, String>> titles = new ArrayList<HashMap<String, String>>();
    	for(int i = 0; i < items.length; i++) {
    		HashMap<String, String> map = new HashMap<String, String>();
    		map.put("title", items[i][1]);
    		titles.add(map);
    	}
    	titlesAdatper = new SimpleAdapter(context, titles, 
    			R.layout.items, new String[]{"title"}, new int[] {R.id.ItemText});
    	gv_titles.setAdapter(titlesAdatper);
    	
    	//点击字段标题，改变排序方式
    	gv_titles.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch(arg2)
				{					
					case 0:
						if(isDesc[arg2]) {		
							OrderedByCityName(true);
							isDesc[arg2] = false;
						}else {		
							OrderedByCityName(false);
							isDesc[arg2] = true;
						}	
						break;
					case 1:
						if(isDesc[arg2]) {		
							OrderedByFoodName(true);
							isDesc[arg2] = false;
						}else {		
							OrderedByFoodName(false);
							isDesc[arg2] = true;
						}	
						break;
					case 2:
						if(isDesc[arg2]) {		
							OrderedByPrice(true);
							isDesc[arg2] = false;
						}else {		
							OrderedByPrice(false);
							isDesc[arg2] = true;
						}	
						break;
					case 3:
						if(isDesc[arg2]) {		
							OrderedBypriceDate(true);
							isDesc[arg2] = false;
						}else {		
							OrderedBypriceDate(false);
							isDesc[arg2] = true;
						}						
						break;
					default:						
						break;
				}			
				toPage(0);
			}
		});
    }
    
    /*按照priceDate进行排序
     *  
     */
    public void OrderedBypriceDate(boolean assend)
    {
    	History p,q;
    	int count = this.histories.size();
    	int i, j;
    	//先按照升序排列    	
    		for(i = 0; i < count -1; i++)
    		{
    			for(j = count -1; j > i; j--)
    			{
    				p = this.histories.get(j);
    				q = this.histories.get(j-1);
    				if(p.getDate().compareToIgnoreCase(q.getDate())<0)
    				{
    					this.histories.set(j, q);
    					this.histories.set(j-1, p);
    				}
    			}
    		} 	
    	
    	//降序
    	if(!assend)
    	{
    		Collections.reverse(this.histories);
    	}
    }
    
    /*按照市场名字进行排序
     * 
     */
    public void OrderedByCityName(boolean assend)
    {
    	History p,q;
    	int count = this.histories.size();
    	int i, j;
    	//先按照升序排列    	
    		for(i = 0; i < count -1; i++)
    		{
    			for(j = count -1; j > i; j--)
    			{
    				p = this.histories.get(j);
    				q = this.histories.get(j-1);
    				if(p.getCity().compareToIgnoreCase(q.getCity())<0)
    				{
    					this.histories.set(j, q);
    					this.histories.set(j-1, p);
    				}
    			}
    		} 	
    	
    	//降序
    	if(!assend)
    	{
    		Collections.reverse(this.histories);
    	}
    }
    
    /*按照菜的种类进行排序
     * 
     */
    public void OrderedByFoodName(boolean assend)
    {
    	History p,q;
    	int count = this.histories.size();
    	int i, j;
    	//先按照升序排列    	
    		for(i = 0; i < count -1; i++)
    		{
    			for(j = count -1; j > i; j--)
    			{
    				p = this.histories.get(j);
    				q = this.histories.get(j-1);
    				if(p.getFood().compareToIgnoreCase(q.getFood())<0)
    				{
    					this.histories.set(j, q);
    					this.histories.set(j-1, p);
    				}
    			}
    		} 	
    	
    	//降序
    	if(!assend)
    	{
    		Collections.reverse(this.histories);
    	}
    }
    
    /*按照菜价进行排序
     * 
     */
    public void OrderedByPrice(boolean assend)
    {
    	History p,q;
    	int count = this.histories.size();
    	int i, j;
    	//先按照升序排列    	
    		for(i = 0; i < count -1; i++)
    		{
    			for(j = count -1; j > i; j--)
    			{
    				p = this.histories.get(j);
    				q = this.histories.get(j-1);
    				if(Float.parseFloat(p.getPrice())<Float.parseFloat(q.getPrice()))
    				{
    					this.histories.set(j, q);
    					this.histories.set(j-1, p);
    				}
    			}
    		} 	
    	
    	//降序
    	if(!assend)
    	{
    		Collections.reverse(this.histories);
    	}
    }
    
    
    /**
     * 设置表格数据视图
     */
    private void setBody() {
    	gv_body = new GridView(context);
    	gv_body.setNumColumns(items.length);
    		
    	toPage(0);	//转到第一页
    	gv_body.setOnItemLongClickListener(this);
    	gv_body.setOnItemClickListener(this);	//点击数据事件
    	
    	
    }
    
    /**
     * 设置底部翻页视图，
     * 由如下组成：首页、上一页、下一页、尾页、页码选择、当期页码提示
     */
    private void setBottomLayout() {
    	//底部容器
    	bottomLayout = new LinearLayout(context);
    	bottomLayout.setOrientation(LinearLayout.HORIZONTAL);
    	bottomLayout.setLayoutParams(new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    	//翻页按钮
    	bt_pre = new Button(context);	//上一页
    	bt_next = new Button(context);	//下一页
    	bt_first = new Button(context);	//首页
    	bt_last = new Button(context);	//尾页    
    	
    	//刷新按钮
    	bt_refresh = new Button(context);
    	//设置文本
    	bt_pre.setText("上一页");
    	bt_next.setText("下一页");
    	bt_first.setText("首页");
    	bt_last.setText("尾页");    	
    	bt_refresh.setText("刷新");
    	
    	//设置事件
    	
    	bt_first.setOnClickListener(this);
    	bt_pre.setOnClickListener(this);
    	bt_last.setOnClickListener(this);
    	bt_next.setOnClickListener(this);
    	//定义刷新事件
    	bt_refresh.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View arg0) {
				refresh();
				
			}
    		
    	});
    	
    	//设置文本大小
    	bt_first.setTextSize(10);
    	bt_pre.setTextSize(10);
    	bt_last.setTextSize(10);
    	bt_next.setTextSize(10);
    	bt_refresh.setTextSize(10);
    	
    	//添加到底部容器
    	bottomLayout.addView(bt_first);
    	bottomLayout.addView(bt_pre);
    	bottomLayout.addView(bt_next);
    	bottomLayout.addView(bt_last);  
    	bottomLayout.addView(bt_refresh);
    }

    //设置显示大小
    public void setSize(View v) {
    	v.setLayoutParams(new android.view.ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    }
    
    /**
     * 翻页点击事件
     */
	@Override
	public void onClick(View v) {

		if(v == bt_first) {	//第一页
			pageID = 0;
				
		}else if(v == bt_last) {	//最后一页
			if(pageCount == 0) {
				DisplayToast("您没有操作历史记录",Toast.LENGTH_SHORT);
				return;
			}
			pageID = pageCount;
			toPage(pageID);
		}else if(v == bt_next) {	//下一页
			if(pageID < pageCount) {
				++pageID;
				toPage(pageID);
			} else {
				DisplayToast("已经到达尾页",Toast.LENGTH_SHORT);
				return;
			}
			
		}else if(v == bt_pre) {	//上一页
			if(pageID <= 0){
				DisplayToast("已经到达首页",Toast.LENGTH_SHORT);
				return;
			}else {
				--pageID;
				toPage(pageID);
			}
		}		
		
	}
	
	/**
	 * 跳转页面
	 * @param startIndex 开始页码
	 * @param sql 查询语句
	 */
	public void toPage(int startIndex) 
	{				
		//获取查询结果集合
		ArrayList<HashMap<String, String>>  temp = query2(context, fields);				
		int index = startIndex*this.TableRowCount*this.items.length;
		int endIndex = Math.min(temp.size()-1,(index+this.items.length-1 + (this.TableRowCount -1)*this.items.length));
		//清空原来的数据
		dataList.clear();
		//添加新的数据
		for(int i = index; i <= endIndex; i++)
		{
			dataList.add(temp.get(i));
		}
    	//设置适配器
    	SimpleAdapter simpleAdapter = new SimpleAdapter(context, dataList, 
    			R.layout.items, new String[]{"item"}, new int[] {R.id.ItemText});
    	gv_body.setAdapter(simpleAdapter);	//重新添加适配器
	}
	
	public  ArrayList<HashMap<String,String>>  query2(Context context,  String[] fields) 
	{
		
		ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
		History temp;			
		HashMap<String, String> map;
	    Iterator<History> it = histories.iterator();
		while(it.hasNext())
		{				
			temp = it.next();			
			map = new HashMap<String, String>();
			map.put("item", temp.getCity());
			dataList.add(map);
			map = new HashMap<String, String>();
			map.put("item", temp.getFood());
			dataList.add(map);
			map = new HashMap<String, String>();
			map.put("item", String.valueOf(temp.getPrice()));
			dataList.add(map);			
			map = new HashMap<String, String>();
			map.put("item", String.valueOf(temp.getDate()));
			dataList.add(map);
		}
		return dataList;
	}	

	/**
	 * 数据项点击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{	
		final History selectedHistory;
		AlertDialog showChangeDialog;		
		int index = TableRowCount * pageID +arg2/items.length;
		//DisplayToast("index = "+index,Toast.LENGTH_SHORT);
		selectedHistory = findHistory(index);
		if(selectedHistory != null)
		{
					 showChangeDialog = new AlertDialog.Builder(arg1.getContext()).setTitle("请选择操作").setIcon(
				     android.R.drawable.ic_dialog_info).setSingleChoiceItems(
				     new String[] { "修改菜价信息", "删除提交的菜价" }, 0,
				     new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {
				    	  switch(which)
				    	  {
				    	  		//修改
				    	  		case 0:
				    	  			dialog.cancel();
				    	  			showModifyDialog(selectedHistory);				    	  			
				    	  			break;
				    		  //删除
				    	  		case 1:
				    	  			dialog.cancel();
				    	  			showDeleteDialog(selectedHistory);
				    	  			break;
				    	  }	
				    	//更新history
				    	  refresh();
				    	  
				      }
				     }).setNegativeButton("取消", null).show();
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) 
	{	
			Toast.makeText(context, ((HashMap<String, String>)dataList.get(arg2)).get("item"), 
					Toast.LENGTH_SHORT).show();
			return true;
	}
	
	public History findHistory(int index)
	{
			if(index < 0 || index >= histories.size())
			{
				return null;
			}
			else
			{
				return histories.get(index);
			}
			
	}
	
	
	//修改菜价	
    protected void showModifyDialog(final History history) 
    {    	  
        LayoutInflater factory = LayoutInflater.from(this.context);  
        final View textEntryView = factory.inflate(R.layout.newmarketfood_dialog, null);
        final TextView city_TextView = (TextView) textEntryView.findViewById(R.id.city_dialog_textview1);
        city_TextView.setText(String.valueOf(history.getCityId()));          
        final TextView foodName_TextView = (TextView)textEntryView.findViewById(R.id.foodname_dialog_textview1);
        foodName_TextView.setText(String.valueOf(history.getFoodId()));
        final EditText foodPrice_editText = (EditText)textEntryView.findViewById(R.id.foodprice_dialog_edittext);
        foodPrice_editText.setText(String.valueOf(history.getPrice()));        
        AlertDialog.Builder ad1 = new AlertDialog.Builder(this.context);  
        ad1.setTitle("修改菜价");  
        ad1.setView(textEntryView);  
        ad1.setPositiveButton("提交", new DialogInterface.OnClickListener() {  
            public void onClick(DialogInterface dialog, int i) 
            {            	        						 
            					foodprice = foodPrice_editText.getText().toString();
            					try            				
        						{ 
        							Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); 
        							field.setAccessible(true); 
        							field.set(dialog, true); 
        						}
        						catch (Exception e) 
        						{ 
        							e.printStackTrace(); 
        						}      
            					//此处显示可以改成等待的那个对话框
            					DisplayToast("提交中......",Toast.LENGTH_SHORT);
        						date = TimeFormatTransform.getCurrentDate();
        						//连接服务器，将信息传给服务器端       
        						try {
									url = new URL("http://"+Constants.serverIP+":8080/MobileCityServer/updateQuote.do?"
																+"userId="+Session.user.getId()
																+"&cityId="+ history.getCityId()
																+"&foodId="+ history.getFoodId()
																+"&price="+foodprice
																+"&priceDate="+date);
									//DisplayToast(url.toString() ,Toast.LENGTH_SHORT);
									result = HttpConnection.httpConnection(url);
									if(result.compareToIgnoreCase("success")==0)
									{
										DisplayToast("修改菜价成功!",Toast.LENGTH_SHORT);
									}
									else
									{
										DisplayToast("修改菜价失败",Toast.LENGTH_SHORT);
									}
								} catch (MalformedURLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}        						
            			
            		}            
        });  
        ad1.setNegativeButton("取消", new DialogInterface.OnClickListener() {  
            public void onClick(DialogInterface dialog, int i)
            {        
            	try { 
    				Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); 
    				field.setAccessible(true); 
    				field.set(dialog,true); 
    				} catch (Exception e) { 
    				e.printStackTrace(); 
    				}  
            }  
        });  
        ad1.show();
        
    }  
    
    //显示信息
	public void DisplayToast(String str,int time)   
	{  
		toast = Toast.makeText(this.context, str, time);       
		//设置toast显示的位置             	
		toast.setGravity(Gravity.TOP, 0, 320);         
		//显示该Toast       	
		toast.show();    	
	}
	
	//删除确认对话框
	public void showDeleteDialog(final History selectedHistory)
	{		
		new AlertDialog.Builder(this.context)
        /**设置标题**/
        .setTitle("删除")
        /**设置icon**/
        .setIcon(android.R.drawable.alert_dark_frame)
        /**设置内容**/
        .setMessage("你确定要删除此条菜价吗？")
        .setNegativeButton("取消", new DialogInterface.OnClickListener(){

            public void onClick(DialogInterface dialog, int which) 
            {
                dialog.cancel();     
                
            }}).setPositiveButton("确定", new DialogInterface.OnClickListener(){

                private String date;

				public void onClick(DialogInterface dialog, int which) 
                {                	
                	date = TimeFormatTransform.getCurrentDate();
                    //连接服务器
                	try {
						url = new URL("http://"+Constants.serverIP+":8080/MobileCityServer/deleteQuote.do?"
												+"userId="+Session.user.getId()
												+"&cityId="+ selectedHistory.getCityId()
												+"&foodId="+selectedHistory.getFoodId()
												+"&priceDate="+date);		
						result = HttpConnection.httpConnection(url);
						if(result.compareToIgnoreCase("success")==0)
						{
							DisplayToast("删除菜价成功!",Toast.LENGTH_SHORT);
						}
						else
						{
							DisplayToast("删除菜价失败",Toast.LENGTH_SHORT);
						}						
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}                       
                    dialog.cancel();
                }}).show();

	}
	
	
}